package com.demo.io.bio.server;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author libo
 * @version 1.0
 * @date 2018/5/29 10:11
 */
public class Server {

    private static final int PORT = 12345;
    private volatile static ServerSocket server;

    public synchronized static void start() throws IOException {
        start(PORT);
    }

    public synchronized static void start(int port) throws IOException {
        if (server != null) {
            return;
        }

        try {
            server = new ServerSocket(port,3);
            System.out.println("服务端已启动，端口号：" + port);
            while (true) {
                Socket socket = server.accept();
                System.out.println("客户端加入连接：" + socket.getInetAddress());
                process(socket);
            }
        }finally {
            if (server != null) {
                System.out.println("服务端已关闭");
                server.close();
                server = null;
            }
        }
    }

    private static void process(Socket socket) {
        BufferedReader br = null;
        PrintWriter pw = null;
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            pw = new PrintWriter(socket.getOutputStream(), true);
            String expression= br.readLine();
            System.out.println("服务端收到消息：" + expression);
            pw.println("你好：" + expression + "！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
                pw = null;
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }
        }
    }

}
